//
//  DHNewsDetail_WebCell.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/5/28.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHNewsDetail_WebCell.h"

@interface DHNewsDetail_WebCell()<WKNavigationDelegate, WKUIDelegate>

@property (assign, nonatomic) BOOL isCollect; //是否收藏
@property (strong, nonatomic) NSDictionary *dic; //数据

@property (assign, nonatomic) int likeCount;

@end

@implementation DHNewsDetail_WebCell

- (void)awakeFromNib {
    [super awakeFromNib];

    if (!_webView) {
        WKWebViewConfiguration *config = [WKWebViewConfiguration new];
        //初始化偏好设置属性：preferences
        config.preferences = [WKPreferences new];
        //The minimum font size in points default is 0;
        config.preferences.minimumFontSize = 10;
        //是否支持JavaScript
        config.preferences.javaScriptEnabled = YES;
        //不通过用户交互，是否可以打开窗口
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        config.selectionGranularity = WKSelectionGranularityCharacter;
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, self.height - 60) configuration:config];
        _webView.UIDelegate =self;
        _webView.navigationDelegate = self;
        // 此处因为高度自适应所以不应该让webview内部可以滚动
        _webView.scrollView.scrollEnabled = NO;
        [self.contentView insertSubview:_webView atIndex:0];
    }

    WeakSelf(weakSelf)
    [self.likeButton bk_addEventHandler:^(id sender) {
        if (weakSelf.isCollect) {
            [weakSelf.likeButton setImage:[UIImage imageNamed:@"product_unlike"] forState:UIControlStateNormal];
            weakSelf.likeCount -= 1;
            weakSelf.likeLabel.text = [NSString stringWithFormat:@"%d个赞",self.likeCount];
            [[DHNetAPIClient shareDHNetAPIClient] request_articles_collectWithParams:@{@"article_id":[weakSelf.dic objectForKey:@"_id"],@"collect":[NSNumber numberWithBool:!weakSelf.isCollect]} andBlock:^(id data, NSError *error) {
                weakSelf.isCollect = NO;
            }];
        }else{
            [weakSelf.likeButton setImage:[UIImage imageNamed:@"product_like"] forState:UIControlStateNormal];
            weakSelf.likeCount += 1;
            weakSelf.likeLabel.text = [NSString stringWithFormat:@"%d个赞",self.likeCount];
            [[DHNetAPIClient shareDHNetAPIClient] request_articles_collectWithParams:@{@"article_id":[weakSelf.dic objectForKey:@"_id"],@"collect":[NSNumber numberWithBool:!weakSelf.isCollect]} andBlock:^(id data, NSError *error) {
                weakSelf.isCollect = YES;
            }];
        }
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)updateCell:(NSDictionary *)dic{
    
    self.dic = dic;
    self.isCollect = [[dic objectForKey:@"collected"] boolValue];
    
    if (dic) {
        [self.webView loadHTMLString:[dic objectForKey:@"content"] baseURL:nil];
    }
    
    
    if ([dic objectForKey:@"collected_count"]) {
        self.likeCount = [[dic objectForKey:@"collected_count"] intValue];
    }else{
        self.likeCount = 0;
    }
    self.likeLabel.text = [NSString stringWithFormat:@"%d个赞",self.likeCount];
    
    if (self.isCollect) {
        [self.likeButton setImage:[UIImage imageNamed:@"product_like"] forState:UIControlStateNormal];
    }else{
        [self.likeButton setImage:[UIImage imageNamed:@"product_unlike"] forState:UIControlStateNormal];
    }
}

- (void)layoutSubviews{
    self.webView.frame = CGRectMake(0, 0, kScreenWidth, self.height - 60);
    self.bottomView.top = self.height - 60;
}
#pragma mark - UIWebViewDelegate
/**
 *  页面加载完成之后调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完毕");
//    CGFloat webViewHeight = webView.scrollView.contentSize.height;
//    NSLog(@"webViewHeight:::%f",webViewHeight);
//    NSLog(@"webViewHeight:::%@",[NSNumber numberWithFloat:webViewHeight]);
    
    self.height = webView.frame.size.height;
    //获取内容实际高度（像素）@"document.getElementById(\"content\").offsetHeight;"
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
        // 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度，看参考资料说是对于加载html字符串的情况下使用后者可以，但如果是和我一样直接加载原站内容使用前者更合适
        //获取页面高度，并重置webview的frame
        CGFloat webViewHeight = [result floatValue];
        NSLog(@"%f",webViewHeight);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (webViewHeight != self.height) {
//                webView.frame = CGRectMake(0, 0, self.view.frame.size.width, webViewHeight);
//                [self.tableView reloadData];

                self.bottomView.top = self.height - 60;
                
                [self routerEventWithName:@"webViewDidFinishLoad" userInfo:@{@"height":[NSNumber numberWithFloat:webViewHeight]}];
            }
        });
    }];
}
//- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    NSLog(@"加载完毕");
//    CGFloat webViewHeight = webView.scrollView.contentSize.height;
//    NSLog(@"webViewHeight:::%f",webViewHeight);
//    NSLog(@"webViewHeight:::%@",[NSNumber numberWithFloat:webViewHeight]);
//    [self routerEventWithName:@"webViewDidFinishLoad" userInfo:@{@"height":[NSNumber numberWithFloat:webViewHeight]}];
//}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
